package com.axend.aerosense.room.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.bean.WardSelectItemBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.ui.activity.PeoplePickerActivity;
import com.axend.aerosense.room.ui.adapter.WardProviderMultiAdapter;
import com.axend.aerosense.room.viewmodel.RoomWardViewModel;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentWardSettingBinding;
import com.axend.aerosense.room.entity.WardListResult;

import java.util.ArrayList;
import java.util.List;

/**
 * 被监护人列表界面,用户在此选择被监护人(非新增界面)
 */
public class RoomWardSelectFragment extends MvvmBaseFragment<RoomFragmentWardSettingBinding, RoomWardViewModel>
        implements ILoadDataResult<WardListResult>, IComplete {
    private WardProviderMultiAdapter adapter;
    private ArrayList<WardSelectItemBean> wardInfo = new ArrayList<WardSelectItemBean>();
    boolean selectMode = false; // 是否为选择模式
    // 已经选择的受监护人
    String uuid = null;
    private WardSelectItemBean selectWard= null;
    public final static String ROOM_TYPE = "ROOM_TYPE";
    public final static String UUID = "UUID";
    public final static String SELECT_WARD = "selectWard";

    public static RoomWardSelectFragment getInstance(boolean selectMode, String uid){
        RoomWardSelectFragment fragment = new RoomWardSelectFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(ROOM_TYPE, selectMode);
        bundle.putString(UUID, uid);
        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if(null != bundle){
            selectMode = bundle.getBoolean(ROOM_TYPE, false);
            uuid = bundle.getString(UUID);
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.WARD_COUNT_CHANGE ,Integer.class)
                .observe(getViewLifecycleOwner(), bean-> {
                    viewModel.onLoad();
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if(selectMode){
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_select_ward2));
            // 选择模式
//            ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_complete));
            ((PeoplePickerActivity)getActivity()).setRightTitle("");
            if(null == selectWard){
                ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
            }else{
                ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
            }

        }else{
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_select_ward));
            // 展示模式
            ((PeoplePickerActivity)getActivity()).setRightTitle("");
        }

    }

    private void initView() {
        setLoadSir(viewDataBinding.roomFragmentConent);
        showLoading();
        viewModel.onLoad();
        adapter = new WardProviderMultiAdapter(selectMode);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        viewDataBinding.roomPersonRecyclerview.setLayoutManager(layoutManager);
        viewDataBinding.roomPersonRecyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view, position) -> {

            WardSelectItemBean ward = (WardSelectItemBean)adapter.getData().get(position) ;
            String uid = ward.getWardUuid();
            if(selectMode){
                boolean tmp = ward.isSelecte();
                for(WardSelectItemBean bean: (List<WardSelectItemBean>)adapter.getData()){
                    bean.setSelecte(false);
                }
                if(tmp){
                    // 无选择时不可点击保存
                    selectWard = null;
                    ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
                }else{
                    ward.setSelecte(true);
                    selectWard = ward;
                    ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
                }
                adapter.notifyDataSetChanged();
            }else{
                changeFragment(RoomWardSettingFragment.getInstance(uid));
            }

        });
        viewDataBinding.roomAdd.setOnClickListener(v->{
            changeFragment(RoomWardSettingFragment.getInstance(null));
        });
    }
    private void changeFragment(Fragment fragment){
        FragmentUtil.add(getActivity(), ((PeoplePickerActivity)getActivity()).getContentId(), fragment, this, true);
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment_ward_setting;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected RoomWardViewModel getViewModel() {
        BaseViewModelFactroy<WardListResult> baseViewModelFactroy = new BaseViewModelFactroy<WardListResult> (this, this);
        return new ViewModelProvider(this, baseViewModelFactroy).get(RoomWardViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void complete() {
        // 工具栏完成事件
        if(selectMode){
            if( selectWard != null){
                Intent data = new Intent();
                data.putExtra(SELECT_WARD, selectWard);
                getActivity().setResult(RoomSettingFragment.REQUEST_WARD, data);
            }
            getActivity().finish();
        }
    }

    @Override
    public void loadDataSuccess(WardListResult personListResult) {
        selectWard = null;
        if(null != wardInfo && wardInfo.size()>0){
            wardInfo.clear();
        }
        wardInfo.addAll(personListResult.wardInfo);
        if(selectMode){
            // 选择模式 默认不可点击保存,需要用户选择后方可以
            ((PeoplePickerActivity)getActivity()).setRightTitleClickable(false);
            if(!TextUtils.isEmpty(uuid)){
                for(WardSelectItemBean bean :wardInfo){
                    if(bean.getWardUuid().equals(uuid)){
                        bean.setSelecte(true);
                        selectWard = bean;
                        break;
                    }
                }
            }
        }
        adapter.setList(wardInfo);
        if(selectMode && null != selectWard){
            // 选择模式 默认不可点击保存,需要用户选择后方可以
            ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
        }
    }

    @Override
    public void loadDataFail(String decs) {
        ToastUtils.showLong(decs);
        showEmpty();
    }
}
